/*

Copyright (C) 2007 Thomas Geiger (tom.geiger@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

import uk.org.ogsadai.client.toolkit.GenericServiceFetcher;
import uk.org.ogsadai.client.toolkit.Response;
import uk.org.ogsadai.client.toolkit.activity.ActivityRequest;
import uk.org.ogsadai.client.toolkit.activity.ActivityOutput;
import uk.org.ogsadai.client.toolkit.activity.sql.SQLQuery;
import uk.org.ogsadai.client.toolkit.activity.sql.SQLUpdate;
import uk.org.ogsadai.client.toolkit.activity.sql.WebRowSet;
import uk.org.ogsadai.client.toolkit.service.DataService;
import uk.org.ogsadai.client.toolkit.activity.delivery.DeliverFromURL;
import uk.org.ogsadai.client.toolkit.activity.transform.XSLTransform;

/**
 * The OGSADAIClient class encapsulates the basic SQL functionalities of the 
 * OGSA-DAI Client Toolkit. 
 * It also converts the WebRowSet encoded result messages (query, update) of 
 * OGSA-DAI into the Octave (type safe) XML format, by using a XSL 
 * transformation. As this is implemented as an XSLTransform Activity, the 
 * work is handled at server side.
 */
public class OGSADAIClient {

	private boolean connected;
	private String url;
	private String resource;
	private DataService service;
	// path to the xslt transformation
	private static string transformation = "http://www2.students.fh-vorarlberg.ac.at/~tge1468/webrowset2octave.xslt";
	
	/**
	 * Entry point for testing basic client functions 
	 */
	public static void main(String[] args) {
		 
		 OGSADAIClient client = new OGSADAIClient();
		 client.connect("http://localhost:8080/wsrf/services/ogsadai/DataService", "MySQLResource");
		 System.out.println(client.executeQuery("SELECT * from USER"));
		 client.close();
	}
	
	/**
	 * Create a connection to the OGSA-DAI resource.
	 * @param 	The url of the OGSA-DAI service.
	 * @param	The name of the OGSA-DAI resource to use.
	 * @return 	true if the connection is successful.
	 */
	public boolean connect(String url, String resource) {
		
		this.url = url;
	    this.resource = resource;
	    try {
	    	this.service = GenericServiceFetcher.getInstance().getDataService(url, resource);	    	
	    } catch (Exception e) {
        	System.out.println(e.getMessage());
	    }
        if (service != null) {
        	connected = true;
        }
        
        return connected;
	}
	
	/**
	 * Close the connection.
	 */
	public boolean close() {
		this.url = "";
		// TODO: close dataservice, ...
		connected = false;
		return !connected;
	}
	
	/**
	 * Execute a query and transform the result message into the Octave XML format.
	 * @param	The SQL query string
	 * @return	"" if the statement has failed, the result encoded as Octave XML otherwise.
	 */
	public String executeQuery(String sql) {

		String result = "";
		if (connected) {
			
			DeliverFromURL deliver = new DeliverFromURL( transformation );

	        // Construct a query
	        SQLQuery query  = new SQLQuery(sql);
	        WebRowSet rowset = new WebRowSet( query.getOutput() );

	        // Construct the transformation activity
	        XSLTransform transform = new XSLTransform();
	        transform.setXMLInput( rowset.getOutput() );
	        transform.setXSLTInput( deliver.getOutput() );

	        // Construct the request
	        ActivityRequest request = new ActivityRequest();
	        request.add(deliver);
	        request.add(query);
	        request.add(rowset);
	        request.add(transform);
	          
			Response response = null;
	        try {
	        	response = service.perform( request );
	        	result = transform.getOutput().getData();
	        } catch (Exception e) {
	        	System.out.println(e.getMessage());
	        }
		}

		return result;
	}
	
	/**
	 * Execute an update and transform the result message into the Octave XML format.
	 * @param	The SQL update string
	 * @return	"" if the statement has failed, the result encoded as Octave XML otherwise.
	 */
	public String executeUpdate(String sql) {

		String result = "";
		if (connected) {
			
			DeliverFromURL deliver = new DeliverFromURL( transformation );

	        // Construct an update
	        SQLUpdate update  = new SQLUpdate(sql);
	        WebRowSet rowset = new WebRowSet( update.getOutput() );

	        // Construct the transformation activity
	        XSLTransform transform = new XSLTransform();
	        transform.setXMLInput( rowset.getOutput() );
	        transform.setXSLTInput( deliver.getOutput() );

	        // Construct the request
	        ActivityRequest request = new ActivityRequest();
	        request.add(deliver);
	        request.add(update);
	        request.add(rowset);
	        request.add(transform);
			
			Response response = null;
	        try {
	        	response = service.perform( request );
	        	result = transform.getOutput().getData();
	        } catch (Exception e) {
	        	System.out.println(e.getMessage());
	        }
		}

		return result;
	}
}
